/*  
 *  Copyright 2006 Paul Jack.
 *
 *  This file is part of the Dex compiler suite. 
 *  
 *  Dex is free software; you can redistribute it and/or modify it
 *  under the terms of the GNU General Public License as published by the
 *  Free Software Foundation; either version 2 of the License, or (at your
 *  option) any later version.
 *  
 *  Dex is distributed in the hope that it will be useful, but
 *  WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
 *  Public License for more details.
 *  
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 */
package dex.compiler.model.program;


import dex.compiler.model.definition.Definition;
import dex.compiler.model.definition.Unit;


/**
 * Searches for definitions by name.
 */
public class NameSearcher implements Searcher {


	/**
	 * The name of the thing to search for.
	 * This is unqualified.
	 */
	final private String name;
	
	
	/**
	 * The unit of the thing to search for, or null if the unit
	 * is not known.
	 */
	final private String unit;
	
	
	/**
	 * The class of thing to search for.  Must be a subclass of
	 * Definition.
	 */
	final private Class cls;
	

	/**
	 * Constructs a new <code>NameSearcher</code>.
	 * 
	 * @param  cls  the class of thing to search for; must be a subclass
	 *   of Definition
	 * @param  name  the name of the thing to search for; can be qualified
	 *   or unqualified
	 */
	public NameSearcher(Class cls, String name) {
		if (name == null) {
			throw new IllegalArgumentException("name may not be null");
		}
		if (!Definition.class.isAssignableFrom(cls)) {
			throw new IllegalArgumentException("cls must extend Definition");
		}
		this.cls = cls;
		int p = name.lastIndexOf(':');
		if (p >= 0) {
			this.unit = name.substring(0, p);
			this.name = name.substring(p + 1);
		} else {
			this.name = name;
			this.unit = null;
		}
	}
	
	
	/**
	 * Returns the qualified unit to search for.  Or, null if no
	 * unit was specified.  For instance, if this <code>NameSearcher</code>
	 * instance was constructed with the string "dex:core:Object", then
	 * this method would return "dex:core".  If this were constructed
	 * using just "Object", then this method would return null.
	 * 
	 * @return  the qualified unit to search in, or null to search
	 *   imported units
	 */
	public String getQualifiedUnit() {
		return unit;
	}


	/**
	 * Returns true if the given definition matches this search.
	 * 
	 * @param  unit  the unit that owns the definition
	 * @param  d     the definition to test
	 * @return  true if that definition matches, false otherwise
	 */
	public boolean matches(Unit unit, Definition d) {
		if (!(cls.isInstance(d))) {
			return false;
		}
		return d.getName().equals(name);
	}
	
}
